package cn.zl.springbootmqtt.controller;

import cn.zl.springbootmqtt.entity.AlertInfo;
import cn.zl.springbootmqtt.pub.MqttPushClient;
import cn.zl.springbootmqtt.sub.MqttSubClient;
import com.alibaba.fastjson.JSONObject;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.*;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.Random;

/**
 * @Description:
 * @Author: zhanglang
 * @Date: 2020/10/27 14:44
 */
@Api(tags = "订阅发布")
@RestController
@RequestMapping("/topic")
public class MqttController {
    private static final Random RANDOM = new Random();
    @ApiOperationSupport(author = "zllwsy")
    @ApiOperation(value="发布消息", notes="发布消息", produces="application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "word", value = "单词", paramType = "query", required = true, dataType = "String"),
            @ApiImplicitParam(name = "name", value = "名字", paramType = "query", required = true, dataType = "String")
    })
    @GetMapping("/push")
    public void pushTopic(String word,String name) {
        MqttPushClient instance = MqttPushClient.getInstance();
        MqttMessage message = new MqttMessage();
        AlertInfo alertInfo = new AlertInfo();
        alertInfo.setWdaDeviceCode("007");
        alertInfo.setWdaDeviceType("21");
        alertInfo.setWdaAlarmType("1");
        alertInfo.setWdaAlarmTime(new Date());
        alertInfo.setWdaAlarmContent("到底啥数据呀");
        alertInfo.setWdaRemark("我傻了");
        String s = JSONObject.toJSONString(alertInfo);
        message.setPayload(s.getBytes());
        instance.publish("topicPub", message);
    }

    @ApiOperationSupport(author = "zllwsy")
    @ApiOperation(value="订阅消息", notes="订阅消息", produces="application/json")
    @GetMapping("/sub")
    public void subTopic(){
        MqttSubClient instance = MqttSubClient.getInstance();
        instance.subscribe("topicPub");
    }
}
